<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>getSnapshotBeforeUpdate使用场景</title>


    <script src="./js/17react/react.development.js"></script>
    <script src="./js/17react/react-dom.development.js"></script>
    <script src="js/babel.min.js"></script>
    <script src="./js/prop-types.js"></script>
    <style>
        .list{
            width: 200px;
            height: 150px;
            background: skyblue;
            overflow: auto;
        }
        .news{
            height: 30px;
        }
    </style>
</head>
<body>
    <div id="app"></div>
    <script type="text/babel">
       class NewsList extends React.Component{
           state = {
               newsArr:[]
           }
           componentDidMount(){
               // console.log('componentDidMount')
           // 循环定时器,每隔一秒回来一条新闻
               setInterval(()=>{
                   const {newsArr} = this.state
                   // 模拟一条新闻
                   const news = '新闻'+(newsArr.length+1)
                   // 表示新生成的新闻,原来的新闻用...拓展出来
                   this.setState({newsArr:[news,...newsArr]})
                   // console.log('newsArr',newsArr)
                   // console.log('news',news)
               },1000)
           }

           getSnapshotBeforeUpdate(){
               // scrollHeight表示滚动条需要滚动的高度
               return this.refs.list.scrollHeight
           }



           componentDidUpdate(prevProps,prevState,height){
               console.log('componentDidUpdate')
               // scrollTop表示内容区往上窜多少,this.refs.list.scrollHeight表示的是新的高度
               this.refs.list.scrollTop += this.refs.list.scrollHeight - height

           }
           // 初始化渲染、状态更新之后
           render(){
               // console.log('render')
               return (
                   <div className="list" ref="list">
                       {
                           this.state.newsArr.map((n,index)=>{

                               return <div className="news" key={index}>{n}</div>
                           })
                       }
                   </div>
               )
           }
       }
        ReactDOM.render(<NewsList />,document.getElementById('app'))




    </script>
</body>
</html>
